package com.object.ip;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.object.utils.MyQueryWrapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Li Qing
 * date: 2025/5/1 20:39
 * description:
 */
public class IpUtil {

    public static IpInfo getIpAddress(String ipAddress) {
        String html = HttpRequest.get("https://ip.im/" +ipAddress)
                .execute().body();
        Document doc = Jsoup.parse(html);
        Elements rows = doc.select("tr");

        Map<String, String> result = new HashMap<>();

        for (Element row : rows) {
            Elements tds = row.select("td");
            if (tds.size() == 2) {
                String key = tds.get(0).text().trim();
                String value = tds.get(1).select("code, a").first().text().trim();
                result.put(key, value);
            }
        }
        IpInfo info = JSONUtil.toBean(JSONUtil.toJsonStr(result), IpInfo.class);
        return info;
    }

    public static void main(String[] args) {
        String html = HttpRequest.get("https://ip.im")
                .execute().body();
        Document doc = Jsoup.parse(html);
        Elements rows = doc.select("tr");

        Map<String, String> result = new HashMap<>();

        for (Element row : rows) {
            Elements tds = row.select("td");
            if (tds.size() == 2) {
                String key = tds.get(0).text().trim();
                String value = tds.get(1).select("code, a").first().text().trim();
                result.put(key, value);
            }
        }
        IpInfo info = JSONUtil.toBean(JSONUtil.toJsonStr(result), IpInfo.class);
        System.out.println(JSONUtil.toJsonStr(info));
    }
}
